#include "xmlMethod.h"

#include <string.h> 
#include <stdlib.h>
#include <expat.h>
#include <iostream>
#include "util.h"
#include <exception>

using std::exception;

//WARNING! global variables
static char	*last_content; 
static int wordsCount;

void start(void *data, const char *el, const char **attr) {
	for (int i = 0; attr[i]; i += 2) {
		wordsCount += Util::countWords(attr[i + 1]);
	}
}	

void end(void *data, const char *el) {
	wordsCount += Util::countWords(last_content);
}

void handle_data(void *data, const char *content, int length) 
{ 		
	char *tmp = (char*)malloc(length); 
	strncpy(tmp, content, length); 
	tmp[length] = '\0'; 
	data = (void *)tmp; 
	last_content = tmp;				 
} 

int MethodXML::run(const string str){
	try{
		wordsCount = 0;		
		const char *c_str = str.c_str();	
		XML_Parser parser = XML_ParserCreate(NULL);		
		XML_SetElementHandler(parser, start, end);
		XML_SetCharacterDataHandler(parser, handle_data); 
		XML_Parse(parser, c_str, str.length(), XML_TRUE);
		XML_ParserFree(parser);
	}catch (exception e) {			
		throw "Error while parsing";
	}
	return wordsCount;
}
